from django.contrib.auth.hashers import make_password
from django.shortcuts import render

# Create your views here.
from rest_framework.authentication import BasicAuthentication, SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin, RetrieveModelMixin
from rest_framework_simplejwt.authentication import JWTAuthentication

from user.models import VerifyCode, User
from user.serializers import SmsSerializer, RegisterSerializer, UserSerializer
from utils.send_sms import send_sms


class SmsViewSet(CreateModelMixin, GenericViewSet):
    serializer_class = SmsSerializer

    def create(self, request, *args, **kwargs):
        # 获取手机号
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        phone = serializer.validated_data['phone']
        # 发送验证码
        json = send_sms(phone)
        if json.get('code') == 200:
            # 保存到数据库
            vc = VerifyCode.objects.create(phone=phone, code=json.get('obj'))
            if vc:
                return Response(serializer.data, status=200)

        else:
            return Response({'msg': '验证码发送失败', 'status': json.get('obj')}, status=200)


class UserViewSet(CreateModelMixin, UpdateModelMixin, RetrieveModelMixin, GenericViewSet):
    """
    实现用户注册，登录，更新
    """
    queryset = User.objects.all()

    # serializer_class = RegisterSerializer

    # 局部添加定制身份权限认证
    # 设置需要身份验证的类
    authentication_classes = [BasicAuthentication, SessionAuthentication, JWTAuthentication]
    # # 全类权限认证
    # permission_classes = [IsAuthenticated,]

    def get_permissions(self):
        # 定制类内方法权限认证
        if self.action == 'create':
            return []
        else:
            return [IsAuthenticated(),]

    def get_serializer_class(self):
        # 根据不同的动作调用不同的序列化类
        if self.action == 'retrieve':
            # 登录
            return UserSerializer
        elif self.action == 'create':
            # 注册
            return RegisterSerializer
        return UserSerializer

    # 注册
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 加密
        password = make_password(serializer.validated_data['password'])
        serializer.validated_data['password'] = password

        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        from rest_framework import status
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        serializer.save()
